<template>
  <el-menu
    mode="horizontal"
    :default-active="selectedIndex"
    @select="selected"
    background-color="#545c64"
    text-color="#fff"
    active-text-color="#ffd04b"
    style="height: 50px; width: 100%;"
  >
    <el-menu-item index="1"><router-link
        to="/"
        class="custom-link"
      >寻物</router-link></el-menu-item>
    <el-menu-item index="2"><router-link
        to="/lost"
        class="custom-link"
      >找物</router-link></el-menu-item>
    <el-menu-item index="3"><router-link
        to="/AddInfo"
        class="custom-link"
      >添加失物招领</router-link></el-menu-item>
    <el-menu-item index="4"><router-link
        to="/AddLost"
        class="custom-link"
      >添加寻物启事</router-link></el-menu-item>
  </el-menu>
  <div class="form-container">
    <h2>添加物品信息</h2>
    <form
      @submit.prevent="handleSubmit"
      class="form"
    >
      <div class="form-group">
        <label>标题:</label>
        <input
          type="text"
          v-model="formData.title"
        />
      </div>
      <div class="form-group">
        <label>丢失地点:</label>
        <input
          type="text"
          v-model="formData.lostAdd"
        />
      </div>
      <div class="form-group">
        <label>失物描述:</label>
        <textarea v-model="formData.lostInfo"></textarea>
      </div>
      <div class="form-group">
        <label>联系电话:</label>
        <input
          type="text"
          v-model="formData.tel"
        />
      </div>
      <div class="form-group">
        <label>图片:</label>
        <input
          type="file"
          @change="handleFileChange"
        />
      </div>
      <button
        type="submit"
        class="submit-btn"
      >提交</button>
    </form>
  </div>
</template>

<script>
import { ref } from 'vue';
import Bmob from 'hydrogen-js-sdk';
import useRouter from 'vue-router';
import router from '@/router';
import { ElMessage } from 'element-plus'

export default {
  // name: 'AddLostItemForm',
  mounted () {
    const sessionToken = localStorage.getItem('sessionToken');
    if (sessionToken) {
      // 如果sessionToken存在，则用户已登录，可以执行相应的操作
      console.log('用户已登录，sessionToken:', sessionToken);
    } else {
      console.log('用户未登录');
      ElMessage.success('请登录账户');
      router.push('/login')
    };
  },
  setup () {
    // 初始化表单数据
    const formData = ref({
      title: '',
      lostAdd: '',
      lostInfo: '',
      tel: '',
      pic: null,
    });

    // 处理文件选择事件
    const handleFileChange = (e) => {
      formData.value.image = e.target.files[0];
    };

    // 处理表单提交事件
    const handleSubmit = async () => {
      // 确保用户已登录
      const currentUser = Bmob.User.current();
      if (!currentUser) {
        console.log('用户未登录')
        // router.push('/login'); 
        return;
      }

      // 创建Bmob对象并初始化
      Bmob.initialize("f39237a5bdb2a530", "1234567891234567");
      const query = Bmob.Query('lost');

      // 设置表单数据
      query.set('title', formData.value.title);
      query.set('lostAdd', formData.value.lostAdd);
      query.set('lostInfo', formData.value.lostInfo);
      query.set('tel', formData.value.tel);

      // 将用户的 objectId 同步到 lost 表中的 userId 字段
      query.set('userId', currentUser.objectId);
      query.set('username', currentUser.username);
      // 上传图片
      if (formData.value.image) {
        const file = Bmob.File('image.jpg', formData.value.image);
        try {
          const res = await file.save();
          query.set('image', res[0].url); // 图片保存成功后，保存图片的url到数据库
        } catch (error) {
          console.log('上传图片失败:', error);
        }
      }

      // 尝试保存数据到数据库
      try {
        const res = await query.save();
        ElMessage.success('发布成功！');
        console.log('保存成功:', res);
        // 清空表单数据
        formData.value.title = '';
        formData.value.lostAdd = '';
        formData.value.lostInfo = '';
        formData.value.tel = '';
        formData.value.image = null;
      } catch (error) {
        ElMessage.success('发布失败！');
        console.log('保存失败:', error);
      }
    };

    return {
      formData,
      handleFileChange,
      handleSubmit,
    };
  },
};
</script>

<style scoped>
.form-container {
  max-width: 500px;
  margin: 20px auto; /* 添加上边距 */
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  backdrop-filter: blur(10px); /* 添加毛玻璃效果 */
  background-color: rgba(255, 255, 255, 0.5); /* 透明度可调整 */
}

.form {
  display: grid;
  grid-row-gap: 20px;
}

.form-group {
  display: grid;
  grid-template-columns: 100px 1fr;
  align-items: center;
}

label {
  font-weight: bold;
}

input[type="text"],
textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.submit-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn:hover {
  background-color: #0056b3;
}
</style>
